import { FC, useState, useEffect } from 'react';
import ApiCollector from '@/const/apis';
import get from 'lodash/get';
import uniq from 'lodash/uniq'
import useListDivPages from '@/hooks/useListDivPages';
import FetchTips from '@/components/fetchTips';
import Layout from '@/components/layout';
import ListLoader from '@/components/skeleton/listLoader';
import Lines from '@/components/echarts';
import XAxisEcharts from '@/components/xAxisEcharts';
import ContentEcharts from '@/components/contentEcharts';
import styles from './index.module.less';
import Card from '@/components/card';
import ComNavBar from '@/components/comNavBar';
import { Tabs } from '@nutui/nutui-react';
import { routesUrl } from '@/const/routes';
import { useNavigate, useLocation } from 'react-router';
import useMockRequest from '@/hooks/useMockRequest';
import { Checkbox } from '@nutui/nutui-react';
import icon from '@/images/icon.png'
import checkedIcon from '@/images/checkedIcon.png'
import magicStore from '@/store/magic';
import dayjs from 'dayjs';
import { returnFloat, returnFloatTime, reSetData } from '@/utils/tool';

const grid = {
    top: "32%",
    bottom: '5%',
    left: '6%',
    right: '6%',
}

const style = {
    '--nutui-tabs-titles-item-active-color': "rgb(0, 145, 255)",
    "--nutui-tabs-titles-background-color": "#fff",
    "--nutui-tabs-horizontal-tab-line-color": "#0091FF",
    "--nutui-tabs-titles-item-color": "rgba(0, 0, 0, 0.5)",
    "--nutui-tabs-titles-item-active-font-weight": 500,
    "--nutui-tabs-tab-line-color": "#0091FF",
    "--nutui-tabs-tab-line-width": "28px"
}

const SystemList = () => {
    const navigate = useNavigate();
    const { pathname } = useLocation();
    const list = []
    const ifDone = false
    const listLoading = true
    // const { loading: listLoading, list, ifDone } = useListDivPages('echartsList_content', ApiCollector.getSysList, {});  后期分页

    const [tab4value, setTab4value] = useState(0);
    const [activeCheck, setActiveCheck] = useState({
        ciId: '',
        type: 0,

    });
    const [echartsData, setEchartsData] = useState({});
    const [echartsTodayList, setEchartsTodayList] = useState([]);
    const tabTitle = ["健康度", "体验度", "可用率", "响应时间"]
    const [chartSize, setChartSize] = useState(null);
    // 总体指标-双日趋势
    const tabApi = {
        "健康度": ApiCollector.getJkdSrqs,
        "体验度": ApiCollector.getTydSrqs,
        "可用率": ApiCollector.getKylSrqs,
        "响应时间": ApiCollector.getXySrqs,
    }
    const api = {
        "健康度": ApiCollector.getJiankangList,
        "体验度": ApiCollector.getTiyanList,
        "可用率": ApiCollector.getKeyongList,
        "响应时间": ApiCollector.getXiangyingList,
    }
    const tabListType = {
        0: '健康度：分',
        1: '体验度：%',
        2: '可用率：%',
        3: '响应时间：ms',
    }
    const lineFormatterList = {
        0: "分",
        1: "%",
        2: "%",
        3: "ms"
    }

    // console.log('magicStore.appUserId', magicStore.appUserId);
    const { data, error, loading, run: runTab, refresh } = useMockRequest(api[tabTitle[tab4value]], {
        data: { userId: magicStore.appUserId },
        config: {
            refreshDeps: [tab4value],
        }
    });
    const tabDataRequest = useMockRequest(tabApi[tabTitle[tab4value]], {
        config: {
            refreshDeps: [tab4value],
            onSuccess: (result, params) => {
                const data = get(result, 'data.result', [])
                let _timesToday = get(data, 'timesToday', []).map(item => {
                    return dayjs(Number(item)).format('HH:mm')
                })
                let _timesYesterday = get(data, 'timesYesterday', []).map(item => {
                    return dayjs(Number(item)).format('HH:mm')
                })
                let _valuesToday = get(data, 'valuesToday', []).map(item => {
                    if(tab4value == 3){
                        return returnFloatTime(item)
                    }else{
                        return returnFloat(item)
                    }
                })
                let _valuesYesterday = get(data, 'valuesYesterday', []).map(item => {
                    if(tab4value == 3){
                        return returnFloatTime(item)
                    }else{
                        return returnFloat(item)
                    }
                })
                let _time = Number(_timesToday.length) > Number(_timesYesterday.length) ? _timesToday : _timesYesterday
                let time = []
                const int = Math.round(Number(_time.length) / 6)
                reSetData(_time, int).map(ite => {
                    if (ite.length >= int) {
                        time.push(ite[ite.length - 1])
                    }
                })
                setEchartsData({
                    xAxis: [_timesToday, _timesYesterday],
                    time: _timesYesterday,
                    lineData: [
                        {
                            name: '今日',
                            value: [..._valuesToday]
                        },
                        { name: '昨日', value: [..._valuesYesterday] }
                    ]
                })
            }
        }
    });

    const getFollowRequest = useMockRequest(ApiCollector.getFollow, {
        data: { ...activeCheck, userId: magicStore.appUserId },
        config: { manual: true }
    });

    // useEffect(() => {
    //     if (pathname == '/systemList') {
    //         runTab()
    //         tabDataRequest.run()
    //     }
    // }, [])
    useEffect(() => {
        if (data.length && !loading) {
            let newData = []
            if (data.length) {
                data.map(item => {
                    let _timesToday = []
                    let _valuesToday = []
                    if (item.timesToday && item.timesToday.length) {
                        _timesToday = get(item, 'timesToday', []).map(it => {
                            return dayjs(Number(it)).format('HH:mm')
                        })
                    }
                    if (item.timesToday && item.timesToday.length) {
                        _valuesToday = get(item, 'valuesToday', []).map(it => {
                            return returnFloat(it)
                        })
                    }
                    newData.push({
                        ...item,
                        timesToday: _timesToday,
                        valuesToday: _valuesToday
                    })
                })

            }
            setEchartsTodayList(newData)
        }
    }, [pathname, data])



    // useEffect(() => {
    //     if (tabDataRequest.data && !tabDataRequest.loading) {
    //         let _timesToday = get(tabDataRequest, 'data.timesToday', []).map(item => {
    //             return dayjs(Number(item)).format('HH:mm')
    //         })
    //         let _timesYesterday = get(tabDataRequest, 'data.timesYesterday', []).map(item => {
    //             return dayjs(Number(item)).format('HH:mm')
    //         })
    //         let _valuesToday = get(tabDataRequest, 'data.valuesToday', []).map(item => {
    //             return returnFloat(item)
    //         })
    //         let _valuesYesterday = get(tabDataRequest, 'data.valuesYesterday', []).map(item => {
    //             return returnFloat(item)
    //         })
    //         let _time = Number(_timesToday.length) > Number(_timesYesterday.length) ? _timesToday : _timesYesterday
    //         let time = []
    //         const int = Math.round(Number(_time.length) / 6)
    //         // console.log('reSetData(_time, int)', reSetData(_time, int));
    //         reSetData(_time, int).map(ite => {
    //             if (ite.length >= int) {
    //                 time.push(ite[ite.length - 1])
    //             }
    //         })
    //         // if (_time && Number(_time.length) > 99) {
    //         //     const int = Math.round(Number(_time.length) / 6)
    //         //     console.log('reSetData(_time, int)', reSetData(_time, int));
    //         //     time = reSetData(_time, int).map(ite => {
    //         //         return ite[ite.length - 1]
    //         //     })
    //         // }else{
    //         //     const int = Math.round(Number(_time.length) / 6)
    //         //     console.log('reSetData(_time, int)', reSetData(_time, int));
    //         //     time = reSetData(_time, int).map(ite => {
    //         //         return ite[ite.length - 1]
    //         //     })
    //         //     // time = _time
    //         // }
    //         console.log('shijian', time);
    //         setEchartsData({
    //             xAxis: time,
    //             lineData: [
    //                 {
    //                     name: '今日',
    //                     value: [..._valuesToday]
    //                 },
    //                 { name: '昨日', value: [..._valuesYesterday] }
    //             ]
    //         })
    //         // setEchartsTodayList(data)
    //     }
    // }, [pathname, tab4value, tabDataRequest.data])

    useEffect(() => {
        if (activeCheck.type && activeCheck.ciId) {
            getFollowRequest.runAsync().then((data) => {
                if (data.data.code == '200') {
                    refresh()
                }

            }).catch((error) => {
                console.log(error);
            })

        }
    }, [activeCheck])

    const onClickContentEcharts = (data, tab4value) => {
        let timesToday = get(data, 'timesToday', []).map(item => {
            return dayjs(Number(item)).format('HH:mm')
        })
        let timesYesterday = get(data, 'timesYesterday', []).map(item => {
            return dayjs(Number(item)).format('HH:mm')
        })
        let valuesToday = get(data, 'valuesToday', []).map(item => {
            if(tab4value == 3){
                return returnFloatTime(item)
            }else{
                return returnFloat(item)
            }
            
        })
        let valuesYesterday = get(data, 'valuesYesterday', []).map(item => {
            if(tab4value == 3){
                return returnFloatTime(item)
            }else{
                return returnFloat(item)
            }
        })
        let _time = Number(timesToday.length) > Number(timesYesterday.length) ? timesToday : timesYesterday
        let time = []
        const int = Math.round(Number(_time.length) / 6)
        // console.log('reSetData(_time, int)', reSetData(_time, int));
        reSetData(_time, int).map(ite => {
            if (ite.length >= int) {
                time.push(ite[ite.length - 1])
            }
        })
        // console.log('_valuesYesterday', timesToday, timesYesterday,time);
        setEchartsData({
            xAxis: [timesToday, timesYesterday],
            time: timesYesterday,
            lineData: [
                {
                    name: '今日',
                    value: [...valuesToday]
                },
                { name: '昨日', value: [...valuesYesterday] }
            ]
        })
    }

    const onClickToDetail = (item) => {
        if (!item.ciId) return
        navigate(routesUrl.systemDetail, { state: { ciId: item.ciId,ciName:item.ciName}, replace: true });
    };


    useEffect(() => {
        const handleResize = () => {
          const canvas = document.getElementById("lineBox");
          setChartSize({
            width: canvas.offsetWidth,
            height: canvas.offsetHeight
          });
        };
      
        window.addEventListener("resize", handleResize);
        handleResize();
      
        return () => {
          window.removeEventListener("resize", handleResize);
        };
      }, []);
    //   console.log(chartSize,'chartSize111')
    // 如果请求还在加载，则渲染骨架屏
    // if (loading) return <ListLoader />;
    // if (magicStore.magicText === '') return <ListLoader />;
    // console.log('lllll0000',echartsTodayList)
    return <Layout title='陕汽核心系统移动端监控' navbar={true}>

        <div className={styles.bg}>
            <ComNavBar title={"系统列表"} onBackClick={(e) => {
                navigate('/');
            }} />
            <div className={styles.carTabs}>
                <Tabs value={tab4value} duration={0} style={{ ...style }} onChange={(value) => {
                    setTab4value(value)
                }}>
                    {
                        tabTitle.map((item, index) => {
                            return <Tabs.TabPane title={item} key={index}>
                                <div className={styles.carTabs_lines} id="lineBox">
                                    {chartSize && chartSize.width > 0 && tabDataRequest.data && !tabDataRequest.loading && <XAxisEcharts
                                        data={echartsData}
                                        grid={grid}
                                        splitLineShow={false}
                                        yAxisName={`单位 ${lineFormatterList[tab4value]}`}
                                        xAxisInterval={4}
                                        chartSize={chartSize}
                                    />}
                                </div>
                            </Tabs.TabPane>
                        })
                    }
                </Tabs>
            </div>
            <div className={styles.echartsList}>
                <div className={styles.echartsList_title}>
                    <div className={styles.echartsList_title_sys}>系统名称</div>
                    <div className={styles.echartsList_title_today}>今日趋势</div>
                    <div className={styles.echartsList_title_exp}>{tabListType[tab4value]}</div>
                </div>

            </div>

        </div>
        <div className={styles.echartsList_content} id='echartsList_content'>
            {
                echartsTodayList.map((item, index) => (
                    <div className={styles.echartsList_content_item} key={index}>
                        <div className={styles.echartsList_content_flex}>
                            <Checkbox 
                            icon={
                                <div className={styles.checkedIconStyle}>
                                    <img src={icon} />
                                </div>}
                                checked={get(item, 'followType', false)}
                                activeIcon={<div className={styles.checkedIconStyle}>
                                    <img src={checkedIcon} />
                                </div>}
                                onChange={(state) => {
                                    setActiveCheck({
                                        type: state ? 1 : 2,
                                        ciId: get(item, 'ciId', '')
                                    })
                                }}
                                key={index}
                            ></Checkbox>
                            <div className={styles.echartsList_content_title} onClick={() => { onClickToDetail(item) }}>{get(item, 'ciName', '')}</div>
                        </div>

                        <div className={styles.echartsList_content_echarts} onClick={() => {
                            onClickContentEcharts(item,tab4value)
                        }}>
                            <ContentEcharts data={{
                                xAxis: get(item, 'timesToday', []),
                                yAxis: get(item, 'valuesToday', []),
                                tab4value:tab4value
                            }} />
                        </div>
                        <div className={styles.echartsList_content_number}>{tab4value == 0 ? get(item, 'healthScore', 0) : get(item, 'valueRecently', 0)}</div>
                    </div>
                ))
            }
            {/* 底部加载时的请求提示 */}
            {/* <FetchTips ifDone={ifDone} /> */}
        </div>

    </Layout>;

};

export default SystemList;